import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONStringer;


/***********************************************************************
 * Star class
 * 
 * Implements the star artifact
 *
 * Signature:
 *  public static Star create (String name, Coord position);
 *  public void install ();
 *  public void destroy ();
 *  public Coord position ();
 *  public String name ();
 *  public void report (String message);
 *  public void changePosition (Coord target);
 *  public boolean isOrbitable ();
 *  public void takeDamage (int damage);
 *  public abstract char display ();
 *  public abstract String toString ();
 ***********************************************************************/

class Star extends Artifact {

    public Star (String n, Coord p) {
	super(n,p);
    }

    public static Star create (String n, Coord p) {
	Star st = new Star(n,p);
	st.install();
	return st;
    }

    public char display () {
	return '*';
    }

    public String toString () {
	return "Star " + this.name() + " " + this.position().toString();
    }
  
  public String jsonString() {
    return "{Star:[" + name() + "," + position().jsonString() + "]}";
  }

  public static Star fromJSON(JSONObject json) {
    try {
      if(json.getString("className").equals("Star")) {
        return new Star(json.getString("name"),
                        new Coord().fromJSON(json.getJSONObject("position")));
      } else {
        System.err.println("\"" + json.toString() + "\" does not represent a Star.");
        throw new RuntimeException("Cannot parse JSON, it is not a Star!");
      }
    } catch (JSONException e) {
      e.printStackTrace();
      throw new RuntimeException("Unrecoverable JSON error, see above stack trace");
    }
    
  }

  @Override
  public String toJSONString() {
    try {
      return new JSONStringer()
                        .object() 
                          .key("className")
                          .value("Star")
                          .key("name")
                          .value(this.name())
                          .key("position")
                          .value(this.position())
                        .endObject().toString();
    } catch (JSONException e) {
      e.printStackTrace();
      throw new RuntimeException("Unrecoverable JSON error, see above stack trace.");
    }
  }
}


